package com.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.bean.Goods;
import com.mall.bean.GoodsExample;
import com.mall.dao.GoodsMapper;
import com.mall.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public int insert(Goods goods) {
//        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date().toString());
        goods.setCreated_time(new Date());
        goods.setFlag(1);
        return goodsMapper.insertSelective(goods);
    }


    @Override
    public List<Goods> queryData(Goods goods) {
        return null;
    }

    @Override
    public int update(Goods goods) {

        return goodsMapper.updateByPrimaryKeySelective(goods);
    }


    @Override
    public int deleteById(String id) {

//        return goodsMapper.deleteByPrimaryKey(Integer.parseInt(id));
        return 0;
    }

    @Override
    public Goods queryDataById(String id) {
        return null;
    }



    @Override
    public PageInfo<Goods> queryDataByPage(int currentPage, int pageSize, Goods goods) {
        PageHelper.startPage(currentPage,pageSize);
        GoodsExample goosBeanExample = new GoodsExample();
        //按某个条件进查询时，添加QBC查询条件
        GoodsExample.Criteria criteria = goosBeanExample.createCriteria();

        if (goods!=null ){
            criteria.andFlagEqualTo(1);
            if (goods.getGoods_name()!=null && !goods.getGoods_name().equals("")){
                criteria.andGoods_nameLike("%"+goods.getGoods_name()+"%");
            }
            if (goods.getCat_id()!=0 && !goods.getCat_id().equals("")) {
                criteria.andCat_idEqualTo(goods.getCat_id());
            }
        }
        goosBeanExample.setOrderByClause("created_time desc");

        List<Goods> goodsBeanList = goodsMapper.selectGoodCat(goosBeanExample);

        PageInfo<Goods> goodBeanPageInfo = new PageInfo<Goods>(goodsBeanList);
        return goodBeanPageInfo;
    }

    @Override
    public int updateValid(@Validated Goods goods, BindingResult bindingResult) {
        // SpringMVC的是@valid

        GoodsExample goosBeanExample = new GoodsExample();
        //按某个条件进查询时，添加QBC查询条件
        GoodsExample.Criteria criteria = goosBeanExample.createCriteria();

        int i = goodsMapper.updateByPrimaryKey(goods);
        return 0;
    }

    @Override
    public int logicdelete(Goods goods) {
        int deletei = 0;
        if(goods!=null) {
            goods.setFlag(0);
            deletei = goodsMapper.updateByPrimaryKeySelective(goods);
        }
        return deletei;
    }
}
